﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;

namespace AllTalkProxy
{
    public class RoosterManager
    {
        private Dictionary<string, Friend> _friendList;

        public RoosterManager()
        {
            _friendList = new Dictionary<string, Friend>();
        }

        public void UpdatePresence(string presenceResponse)
        {
            if (presenceResponse.Length <= 1)
                return;
            XElement presenceXml = XElement.Parse(presenceResponse);
            Jid jidRecieved = new Jid(presenceXml.Attribute("from").Value);
            //find the friend to update
            Friend friend;
            _friendList.TryGetValue(jidRecieved.UserNameDomain, out friend);
            if (friend == null)
            {
                friend = new Friend(jidRecieved);
            }
            friend.UpdateFriendPresence(jidRecieved, presenceXml);
        }

        public void DisplayFriendList()
        {
            foreach (Friend friend in _friendList.Values)
            {
                Console.WriteLine("Name:"+friend.Name+"\tPic"+friend.Picture+"\tStatus"+friend.Status);
                foreach (Jid jid in friend.Jid)
                {
                    Console.WriteLine("Jid:"+jid.Value + "\t\tShow:" + jid.Presence + "\tPriority:" + jid.Priority);
                }
                Console.WriteLine();
            }
        }

        public void PopulateFriendList(string roosterResponse)
        {
            XNamespace roosterNamespace = "jabber:iq:roster";
            XDocument roosterXml = XDocument.Parse(roosterResponse);
            IEnumerable<XElement> friendElements = roosterXml.Descendants(roosterNamespace + "item");
            foreach (XElement friendNode in friendElements)
            {
                Friend friend = new Friend(friendNode);
                _friendList.Add(friend.Jid.First().UserNameDomain, friend);
            }
        }
    }
}
